import './index.css';
import 'utils/js/px2rem.mobile';
import $ from 'jquery';
import html from './container.html';
import layer from 'utils/js/layer-mobile';
import { apiRoot } from 'utils/js/config';

$('body').html(html);

$('.to-register').click(function () {
  window.location = '/register.html' + window.location.search;
});

$('#doLogin').click(function () {
  var username = $('#username').val();
  if (!username) return layer.msg('请输入账号');
  var password = $('#password').val();
  if (!password) return layer.msg('请输入密码');
  var post_data = { username: username, password: password };
  var loading = layer.load();
  $.ajax({
    url: apiRoot + 'v1/tokens',
    type: 'post',
    contentType: 'application/json',
    dataType: 'json',
    data: JSON.stringify(post_data),
    success: function (res) {
      if (res.code == 200) {
        layer.msg('登录成功');
        window.localStorage.setItem('aichat_token', res.token);
        window.localStorage.setItem('aichat_user_info', JSON.stringify(res.data));
        window.location.replace('/aichat.html' + window.location.search);
      } else {
        layer.msg(res.error);
      }
    },
    error: function (jqXHR, errorType, error) {
      console.error(error);
    }
  }).always(function () {
    layer.close(loading);
  });
});